package com.example.rabbitdemo.listenner;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;

@RocketMQTransactionListener
@Slf4j
public class TransactonMsgConfig  implements RocketMQLocalTransactionListener {
    /**
     * 执行本地事物（在发送消息成功时执行）
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String jsonStr=new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            log.info("执行本地业务，消息为:"+jsonStr);
        } catch (Exception e) {
            log.error("事务执行错误:"+e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        log.info("事务提交，消息正常处理");

        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 检查本地事务状态
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("消息回查");
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
